package com.example.blog.controller;

import com.example.blog.constants.Constant;
import com.example.blog.model.Result;
import com.example.blog.model.UserInfo;
import com.example.blog.service.UserService;
import com.example.blog.utils.JwtUtils;
import com.example.blog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName, String password) {
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码不能为空");
        }
        UserInfo userInfo=userService.queryUserByName(userName);
        if(userInfo==null || userInfo.getId()<0) {
            return Result.fail("用户不存在");
        }
//        if(!password.equals(userInfo.getPassword())) {
//            return Result.fail("密码错误");
//        }
        if (!SecurityUtils.verify(password, userInfo.getPassword())) {
            return Result.fail("密码错误");
        }
        Map<String,Object> claim=new HashMap<String,Object>();
        claim.put(Constant.USER_CLAIM_ID,userInfo.getId());
        claim.put(Constant.USER_CLAIM_NAME,userInfo.getUserName());
        return Result.success(JwtUtils.getToken(claim));
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request) {
        String user_token = request.getHeader(Constant.USER_TOKEN_HEADER);
        Integer userId = JwtUtils.getUserIdFromToken(user_token);
        if(userId==null||userId<=0) {
           return null;
        }
        UserInfo userInfo=userService.queryUserById(userId);
        userInfo.setPassword("");
        return userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {
        if(blogId==null||blogId<=0) {
            return null;
        }
        UserInfo userInfo=userService.getAuthorInfoByBlogId(blogId);
        userInfo.setPassword("");
        return userInfo;
    }
}
